package com.any.hook.common.element;

import com.any.hook.common.exception.CommonErrorCode;
import com.any.hook.common.exception.HookException;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;

public class BoolColumn extends Column {
    public BoolColumn(Boolean bool){
        super(bool, 1, Type.BOOL);
    }
    public BoolColumn(final String data){
        this(true);
        this.validate(data);
        if(null==data){
            this.setRawData(null);
            this.setByteSize(0);
        }else {
            this.setRawData(Boolean.valueOf(data));
            this.setByteSize(1);
        }
    }

    public BoolColumn(){
        super(null,1, Type.BOOL);
    }

    @Override
    public Long asLong() {
        if(null == this.getRawData()){
            return null;
        }
        return this.asBoolean()?1L:0L;
    }

    @Override
    public Double asDouble() {
        if(null == this.getRawData()){
            return null;
        }
        return this.asBoolean()?1.0d:0.0d;
    }

    @Override
    public String asString() {
        if(null == this.getRawData()){
            return null;
        }
        return this.asBoolean()?"true":"false";
    }

    @Override
    public Date asDate() {
        throw HookException.asHookException(CommonErrorCode.CONVERT_NOT_SUPPORT,"Bool类型不能转换为Date .");
    }

    @Override
    public byte[] asBytes() {
        throw HookException.asHookException(CommonErrorCode.CONVERT_NOT_SUPPORT,"Bool类型不能转换为Bytes .");
    }

    @Override
    public Boolean asBoolean() {
        if(null==super.getRawData()){
            return null;
        }
        return(Boolean) super.getRawData();
    }

    @Override
    public BigDecimal asBigDecimal() {
        if (null == this.getRawData()) {
            return null;
        }

        return BigDecimal.valueOf(this.asLong());
    }

    @Override
    public BigInteger asBigInteger() {
        if (null == this.getRawData()) {
            return null;
        }

        return BigInteger.valueOf(this.asLong());
    }

    private void validate(final String data){
        if(null==data || "true".equalsIgnoreCase(data) || "false".equalsIgnoreCase(data)){
            return;
        }
        throw HookException.asHookException(CommonErrorCode.CONVERT_NOT_SUPPORT,String.format("String[%s]不能转为Bool . ",data));

    }
}
